package com.meida.module.bus.provider.controller;

import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.lock.RedissonLocker;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.utils.DateUtils;
import com.meida.module.marketing.client.entity.MkgCoupon;
import com.meida.module.marketing.client.entity.MkgCouponUser;
import com.meida.module.marketing.provider.service.CouponService;
import com.meida.module.marketing.provider.service.CouponUserService;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


/**
 * 赠送优惠券
 *
 * @author flyme
 * @date 2021-08-03
 */
@RestController
@RequestMapping("/couponExtend/")
public class BusCouponExtendController {
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    public RedissonLocker redisLock;

    @ApiOperation(value = "赠送优惠券", notes = "赠送优惠券")
    @PostMapping(value = "givingUser")
    public ResultBody givingUser(Long couponId, Long userId) {
        MkgCoupon mkgCoupon = couponService.getById(couponId);
        if (FlymeUtils.isEmpty(mkgCoupon)) {
            return ResultBody.failed("该优惠券不存在");
        }
        Integer surplusNum = FlymeUtils.getInteger(mkgCoupon.getSurplusNum(), 0);
        if (surplusNum == 0) {
            return ResultBody.failed("该优惠券库存不足");
        }
        RLock lock = redisLock.lock(couponId);
        try {
            //优惠券剩余库存量
            Integer validDays = FlymeUtils.getInteger(mkgCoupon.getValidDays(), 0);
            MkgCouponUser mkgCouponUser = new MkgCouponUser();
            mkgCouponUser.setUserId(userId);
            mkgCouponUser.setCouponId(couponId);
            mkgCouponUser.setUseState(0);
            Date nowDate = DateUtils.getNowDate();
            mkgCouponUser.setUserExpireBeginDate(nowDate);
            Date endDate = DateUtils.plusDateDays(nowDate, validDays);
            mkgCouponUser.setUserExpireEndDate(endDate);
            mkgCouponUser.setIsDelete(0);
            boolean save = couponUserService.save(mkgCouponUser);
            if (save) {
                mkgCoupon.setSurplusNum(surplusNum - 1);
                couponService.updateById(mkgCoupon);
            }
        } finally {
            redisLock.unlock(lock);
        }
        return ResultBody.ok();

    }

}
